//
//  MPTLiveWeiboAutoShare.m
//  MPTLive
//
//  Created by caixun on 15/9/18.
//  Copyright (c) 2015年 Jeakin. All rights reserved.
//

#import "MPTLiveWeiboAutoShare.h"
#import "MPTLogger.h"
#import "MPTTips.h"
#import <MPTLoginApp.h>
#import "MPTValidObject.h"
#import "MBProgressHUD.h"
#import "NSString+MPTString.h"
#import <SDWebImageManager.h>
#import "UIImageView+WebCache.h"
#import "AFHTTPRequestOperationManager.h"
#import "MPTHttpClient.h"
#import "MPTConfig.h"
#import <JLRoutes.h>



@interface MPTLiveWeiboAutoShare()

@property (nonatomic,strong)NSString *liveTitle;


@end

@implementation MPTLiveWeiboAutoShare

- (void)sendWeiboWithScid:(NSString *)scid shareEnum:(ShareEnum)shareEnum image:(UIImage *)image
{
    self.liveTitle = (self.liveTitle == nil || [@"" isEqualToString:self.liveTitle]) ? @"":[NSString stringWithFormat:@"“%@”",self.liveTitle];
    
    NSString *msg;
    if (shareEnum == ZhiBoQian)
    {
        msg= [NSString stringWithFormat:@"我的#秒拍直播#开始了，太多事情想告诉你，来看我的直播吧。http://www.yixia.com/show/%@.htm", scid];
    }
    else if (shareEnum == ZhiBoZhong)
    {
        msg= [NSString stringWithFormat:@"我在#秒拍#等你，来看我直播%@吧，别让我等太久。http://www.yixia.com/show/%@.htm", self.liveTitle,scid];
    }
    else
    {
        
    }
    
    if (msg)
    {
        NSMutableDictionary *parameters = [@{@"status":msg,
                                             @"lat":@(0),
                                             @"long":@(0),
                                             @"annotations":@"[{\"is_original\":0}]"
                                             } mutableCopy];
        [parameters setValue:[MPTConfig loginUser].sinaPaike.weiboToken forKey:@"access_token"];
        
        __block YXRequestLogObject *requestLogObject = [[YXRequestLogObject alloc] init];
        requestLogObject.totalTime = [NSProcessInfo processInfo].systemUptime;
        requestLogObject.sendTime  = 0;
        requestLogObject.receiveTime = 0.0f;
        requestLogObject.userInfo = @"****";
        
        if (image)
        {
            [self shareWithImage:parameters requestLogObject:requestLogObject image:image withShareType:shareEnum];
        }
        else
        {
            NSDictionary *dic = @{@"access_token":ZB_Str_Protect([MPTConfig loginUser].sinaPaike.weiboToken),
                                  @"scid":ZB_Str_Protect(scid)};
            [self shareWithoutImage:dic  withShareType:shareEnum];
        }

    }
}

- (void)setShareInfo:(NSDictionary *)shareInfo
{
    _shareInfo = shareInfo;
}


-(void)setLiveHeadInfo:(NSString *)location withTitle:(NSString *)title
{
    self.liveTitle = title;
}

- (void)shareWithImage:(id)parameters requestLogObject:(YXRequestLogObject*)requestLogObject image:(UIImage *)image withShareType:(ShareEnum)shareEnum
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFJSONResponseSerializer *response= [AFJSONResponseSerializer serializer];
    NSMutableSet *types = [NSMutableSet setWithSet:response.acceptableContentTypes];
    [types addObject:@"json/html"];
    [types addObject:@"text/html"];
    [types addObject:@"text/plain"];
    [types addObject:@"application/json;charset=UTF-8"];
    [types addObject:@"text/javascript"];
    response.acceptableContentTypes = types;
    response.readingOptions = NSJSONReadingMutableContainers;
    manager.responseSerializer = response;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    /// 分享的图片
    NSData *data_image = UIImagePNGRepresentation(image);
    
    [manager POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (data_image)
        {
            [formData appendPartWithFileData:data_image name:@"pic" fileName:@"pic.png" mimeType:@"image/png; charset=UTF-8"];
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        requestLogObject.URL = [NSString stringWithFormat:@"%@ %@?%@",operation.request.HTTPMethod, operation.request.URL, [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding]];
        requestLogObject.IP  = getIPAddressForHost([operation.request.URL host]);
        requestLogObject.totalTime    = ([NSProcessInfo processInfo].systemUptime - requestLogObject.totalTime) * 1000;
        requestLogObject.httpStatusCode        = operation.response.statusCode;
        requestLogObject.receiveByte           = [operation.responseString length];
        requestLogObject.sendByte              = 0;
        requestLogObject.httpResponseString    = operation.responseString;
        
        logger(@"API", extLog(requestLogObject));
        MPTHttpClient *httpClient = [MPTHttpClient sharedMPHTTPClient];
        [httpClient reportShareInfoWithType:3 status:1 scid:self.shareInfo[@"scid"] success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
            NSLog(@"上报成功");
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
        NSLog(@"分享成功啦");
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"分享失败啊");
        requestLogObject.URL = [NSString stringWithFormat:@"%@ %@?%@",operation.request.HTTPMethod, operation.request.URL, [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding]];
        requestLogObject.IP  = getIPAddressForHost([operation.request.URL host]);
        requestLogObject.totalTime    = ([NSProcessInfo processInfo].systemUptime - requestLogObject.totalTime) * 1000;
        requestLogObject.httpStatusCode        = operation.response.statusCode;
        requestLogObject.receiveByte           = [operation.responseString length];
        requestLogObject.sendByte              = 0;
        requestLogObject.httpResponseString    = error.debugDescription;
        
        logger(@"API", extLog(requestLogObject));
        if (operation.response.statusCode >= 400 && operation.response.statusCode < 500) {
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:&error];
            
            NSDictionary *errorMessages = [self weiboErroMessage];
            NSString *errorMessage     = @"微博token失效,请重新绑定或登录";
            
            if (json[@"error_code"])
            {
                errorMessage = errorMessages[[json[@"error_code"] stringValue]];
            }
        }
        else
        {
            [MPTTips showTips:@"同步微博失败,下次启动会继续分享" duration:1.0f];
        }
    }];
    
}

//不是自定义图片的分享
- (void)shareWithoutImage:(id)parameters withShareType:(ShareEnum)shareEnum
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://api.miaopai.com/m/shareWeiboLive.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if(shareEnum == ZhiBoQian)
        {
            [MPTTips showTips:@"秒拍App和新浪微博已同步直播，快跟粉丝们打个招呼～" duration:3.0f];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  
        NSLog(@"分享失败了（原因我也不知道）");
    }];
}


- (NSDictionary *)weiboErroMessage {
    NSDictionary *errorMessage = @{@"20016":@"发微博太多啦，休息一会儿吧",
                                   @"20017":@"你刚刚已经分享过相同的视频了哦，先休息一会吧",
                                   @"20019":@"不要太贪心哦，发一次就够啦",
                                   @"20038":@"您刚才已经分享过相同的视频啦，建议您第二天再尝试",
                                   @"20032":@"微博发布成功。目前服务器数据同步可能会有延迟，\n请耐心等待1-2分钟。谢谢",
                                   @"21601":@"系统繁忙请重试 ",
                                   @"20033":@"登陆状态异常 ",
                                   @"21314":@"Token已经被使用",
                                   @"21315":@"微博token过期,请重新绑定或登录 ",
                                   @"21316":@"Token不合法",
                                   @"21318":@"Pin码认证失败",
                                   @"21319":@" 授权关系已经被解除",
                                   @"21327":@"微博token过期,请重新绑定或登录 ",
                                   @"21332":@"微博token失效,请重新绑定或登录",
                                   @"21334":@"账号状态不正常",
                                   @"21501":@"微博token失效,请重新绑定或登录",
                                   @"21610":@"授权失败"};
    
    return errorMessage;
}


@end
